//
//  ChangeEmailView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI

struct ChangeEmailView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    
    @State private var newEmail = ""
    @State private var oldEmailCode = ""
    @State private var newEmailCode = ""
    @State private var step = 1 // 1: 输入新邮箱, 2: 验证旧邮箱, 3: 验证新邮箱
    @State private var showingAlert = false
    @State private var alertMessage = ""
    @State private var isLoading = false
    @State private var countdown = 60
    @State private var canResendCode = true
    @State private var timer: Timer?
    
    var body: some View {
        NavigationView {
            ZStack {
                Color(.systemGroupedBackground)
                    .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 24) {
                        // 进度指示器
                        HStack {
                            ForEach(1...3, id: \.self) { stepNumber in
                                Circle()
                                    .fill(stepNumber <= step ? Color.orange : Color.gray.opacity(0.3))
                                    .frame(width: 12, height: 12)
                                
                                if stepNumber < 3 {
                                    Rectangle()
                                        .fill(stepNumber < step ? Color.orange : Color.gray.opacity(0.3))
                                        .frame(height: 2)
                                }
                            }
                        }
                        .padding(.horizontal, 40)
                        .padding(.top, 20)
                        
                        // 步骤内容
                        VStack(spacing: 20) {
                            switch step {
                            case 1:
                                step1View
                            case 2:
                                step2View
                            case 3:
                                step3View
                            default:
                                EmptyView()
                            }
                        }
                        .padding(.horizontal, 20)
                    }
                }
            }
            .navigationTitle("更换邮箱")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
            }
        }
        .alert("提示", isPresented: $showingAlert) {
            Button("确定", role: .cancel) { }
        } message: {
            Text(alertMessage)
        }
        .onDisappear {
            timer?.invalidate()
        }
    }
    
    // MARK: - 步骤1: 输入新邮箱
    private var step1View: some View {
        VStack(spacing: 20) {
            VStack(alignment: .leading, spacing: 8) {
                Text("当前邮箱")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Text(dataManager.currentUser?.email ?? "未设置")
                    .font(.title2)
                    .fontWeight(.medium)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            
            VStack(alignment: .leading, spacing: 8) {
                Text("新邮箱地址")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                TextField("请输入新邮箱地址", text: $newEmail)
                    .keyboardType(.emailAddress)
                    .autocapitalization(.none)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
            
            Text("更换邮箱后，您的积分、等级和历史订单等信息将保持不变。")
                .font(.caption)
                .foregroundColor(.secondary)
                .multilineTextAlignment(.center)
            
            Button(action: {
                validateAndProceedToStep2()
            }) {
                Text("下一步")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(isValidEmail(newEmail) ? Color.orange : Color.gray)
                    .cornerRadius(10)
            }
            .disabled(!isValidEmail(newEmail) || isLoading)
        }
        .padding(20)
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
    
    // MARK: - 步骤2: 验证旧邮箱
    private var step2View: some View {
        VStack(spacing: 20) {
            VStack(alignment: .leading, spacing: 8) {
                Text("验证当前邮箱")
                    .font(.headline)
                
                Text("我们已向您的当前邮箱 \(dataManager.currentUser?.email ?? "") 发送验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            
            VStack(alignment: .leading, spacing: 8) {
                Text("验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                TextField("请输入6位验证码", text: $oldEmailCode)
                    .keyboardType(.numberPad)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .onChange(of: oldEmailCode) { newValue in
                        if newValue.count > 6 {
                            oldEmailCode = String(newValue.prefix(6))
                        }
                    }
            }
            
            HStack {
                Button(action: {
                    resendOldEmailCode()
                }) {
                    Text(canResendCode ? "重新发送" : "重新发送(\(countdown))")
                        .font(.subheadline)
                        .foregroundColor(canResendCode ? .orange : .gray)
                }
                .disabled(!canResendCode)
                
                Spacer()
                
                Button("无法接收邮件？") {
                    showManualVerificationAlert()
                }
                .font(.caption)
                .foregroundColor(.blue)
            }
            
            Button(action: {
                validateOldEmailAndProceed()
            }) {
                Text("验证并继续")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(oldEmailCode.count == 6 ? Color.orange : Color.gray)
                    .cornerRadius(10)
            }
            .disabled(oldEmailCode.count != 6 || isLoading)
        }
        .padding(20)
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
    
    // MARK: - 步骤3: 验证新邮箱
    private var step3View: some View {
        VStack(spacing: 20) {
            VStack(alignment: .leading, spacing: 8) {
                Text("验证新邮箱")
                    .font(.headline)
                
                Text("我们已向您的新邮箱 \(newEmail) 发送验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            
            VStack(alignment: .leading, spacing: 8) {
                Text("验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                TextField("请输入6位验证码", text: $newEmailCode)
                    .keyboardType(.numberPad)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .onChange(of: newEmailCode) { newValue in
                        if newValue.count > 6 {
                            newEmailCode = String(newValue.prefix(6))
                        }
                    }
            }
            
            HStack {
                Button(action: {
                    resendNewEmailCode()
                }) {
                    Text(canResendCode ? "重新发送" : "重新发送(\(countdown))")
                        .font(.subheadline)
                        .foregroundColor(canResendCode ? .orange : .gray)
                }
                .disabled(!canResendCode)
                
                Spacer()
            }
            
            Button(action: {
                completeEmailChange()
            }) {
                Text(isLoading ? "处理中..." : "完成更换")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(newEmailCode.count == 6 && !isLoading ? Color.orange : Color.gray)
                    .cornerRadius(10)
            }
            .disabled(newEmailCode.count != 6 || isLoading)
        }
        .padding(20)
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
    
    // MARK: - 方法
    private func isValidEmail(_ email: String) -> Bool {
        let emailPredicate = NSPredicate(format: "SELF MATCHES %@", AppConfig.RegexPatterns.email)
        return emailPredicate.evaluate(with: email)
    }
    
    private func validateAndProceedToStep2() {
        let canChange = dataManager.canChangeEmail()
        guard canChange.canChange else {
            alertMessage = canChange.reason ?? "无法更换邮箱"
            showingAlert = true
            return
        }
        
        guard newEmail != dataManager.currentUser?.email else {
            alertMessage = "新邮箱不能与当前邮箱相同"
            showingAlert = true
            return
        }
        
        guard dataManager.currentUser?.email != nil && !dataManager.currentUser!.email!.isEmpty else {
            alertMessage = "您尚未设置邮箱，请先在个人信息中设置邮箱"
            showingAlert = true
            return
        }
        
        // 发送验证码到旧邮箱
        let oldEmail = dataManager.currentUser?.email ?? ""
        let verificationType = VerificationType.emailChange(oldEmail: oldEmail, newEmail: newEmail)
        let _ = dataManager.sendVerificationCode(for: verificationType)
        
        step = 2
        startCountdown()
    }
    
    private func validateOldEmailAndProceed() {
        let oldEmail = dataManager.currentUser?.email ?? ""
        let verificationType = VerificationType.emailChange(oldEmail: oldEmail, newEmail: newEmail)
        
        guard dataManager.verifyCode(oldEmailCode, for: verificationType) else {
            alertMessage = "验证码错误，请重新输入"
            showingAlert = true
            return
        }
        
        // 发送验证码到新邮箱
        let _ = dataManager.sendVerificationCode(for: verificationType)
        
        step = 3
        startCountdown()
    }
    
    private func completeEmailChange() {
        isLoading = true
        
        let success = dataManager.changeEmail(
            newEmail: newEmail,
            oldEmailCode: oldEmailCode,
            newEmailCode: newEmailCode
        )
        
        isLoading = false
        
        if success {
            alertMessage = "邮箱更换成功！"
            showingAlert = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                dismiss()
            }
        } else {
            alertMessage = "更换失败，请检查验证码是否正确"
            showingAlert = true
        }
    }
    
    private func resendOldEmailCode() {
        let oldEmail = dataManager.currentUser?.email ?? ""
        let verificationType = VerificationType.emailChange(oldEmail: oldEmail, newEmail: newEmail)
        let _ = dataManager.sendVerificationCode(for: verificationType)
        startCountdown()
    }
    
    private func resendNewEmailCode() {
        let oldEmail = dataManager.currentUser?.email ?? ""
        let verificationType = VerificationType.emailChange(oldEmail: oldEmail, newEmail: newEmail)
        let _ = dataManager.sendVerificationCode(for: verificationType)
        startCountdown()
    }
    
    private func showManualVerificationAlert() {
        alertMessage = "如果您无法接收到邮件验证码，请联系客服进行人工验证。客服将协助您完成邮箱更换。"
        showingAlert = true
    }
    
    private func startCountdown() {
        canResendCode = false
        countdown = 60
        
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
            countdown -= 1
            if countdown <= 0 {
                canResendCode = true
                timer?.invalidate()
            }
        }
    }
}

#Preview {
    ChangeEmailView()
        .environmentObject(DataManager.shared)
}